package com.zhudi.job;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhudi.model.entity.User;
import com.zhudi.service.UserService;
import com.zhudi.utils.RedisUtil;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.zhudi.contant.RedisContant.REDIS_RECOMMEND_PAGE_KEY;

@Component
public class CacheJob {


    @Resource
    private RedissonClient redissonClient;

    @Resource
    private UserService userService;

    //todo：暂时设定为只为我自己的号缓存，后面有好的想法再来决定要为谁缓存
    private List<Long> mainUserList = Collections.singletonList(40002L);
    @Scheduled(cron = "0 5 2 * * *")
    public void pageCache(){

        //定时将数据写入缓存
        RLock lock = redissonClient.getLock("partnerMacth:preCacheJob:docache:lock");
        try {
            //尝试加锁，如果成功了，就读取，写入数据
            if(lock.tryLock(3,60, TimeUnit.SECONDS)){
                System.out.println("getLock: " + Thread.currentThread().getId());
                //先获取第一页的前20个数据写入缓存，后期要的话再特别更改

                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                //todo 这里的用户数据要改为是获取推荐后的数据
                Page<User> userPage = userService.page(new Page<>(1, 20), queryWrapper);

                for (Long userId : mainUserList) {
                    //todo:这里要缓存多少数据是写死的不太好，后期再看要怎么改
                    String redisKey = String.format(REDIS_RECOMMEND_PAGE_KEY, userId,1,20);

                    RedisUtil.set(redisKey,userPage,30);
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //这里要注意要加上判断是否是自己的锁，只能释放自己的锁
            if(lock.isHeldByCurrentThread()){
                System.out.println("unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }


    }



}
